import React, { useState, useEffect } from 'react'
import {
  Card,
  Button,
  Space,
  Typography,
  message,
  Alert,
  Statistic,
  Row,
  Col,
} from 'antd'
import {
  PlusOutlined,
  DatabaseOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import ConnectionForm from '@/components/Connection/ConnectionForm'
import ConnectionList from '@/components/Connection/ConnectionList'
import ConnectionStats from '@/components/Connection/ConnectionStats'
import DatabaseSchema from '@/components/Connection/DatabaseSchema'
import type { Connection, CreateConnectionData, UpdateConnectionData, ConnectionTestResult } from '@/types/connection'
import {
  getConnections,
  createConnection,
  updateConnection,
  deleteConnection,
  testConnection,
} from '@/services/connectionAPI'

const { Title } = Typography

const ConnectionManager: React.FC = () => {
  const [connections, setConnections] = useState<Connection[]>([])
  const [loading, setLoading] = useState(false)
  const [formVisible, setFormVisible] = useState(false)
  const [statsVisible, setStatsVisible] = useState(false)
  const [schemaVisible, setSchemaVisible] = useState(false)
  const [editingConnection, setEditingConnection] = useState<Connection | undefined>()
  const [selectedConnection, setSelectedConnection] = useState<Connection | null>(null)
  const [formLoading, setFormLoading] = useState(false)

  // 加载连接列表
  const loadConnections = async () => {
    setLoading(true)
    try {
      const response = await getConnections()
      if (response.success) {
        setConnections(response.data.connections)
      }
    } catch (error) {
      console.error('Failed to load connections:', error)
      message.error('加载连接列表失败')
      // 使用模拟数据
      const mockConnections: Connection[] = [
        {
          id: '1',
          name: '生产环境-Doris',
          host: '192.168.1.100',
          port: 9030,
          username: 'admin',
          database_name: 'warehouse',
          description: '生产环境数据仓库',
          is_active: true,
          created_at: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
          updated_at: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(),
          last_used_at: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
        },
        {
          id: '2',
          name: '测试环境-Doris',
          host: '192.168.1.101',
          port: 9030,
          username: 'test_user',
          database_name: 'test_db',
          description: '测试环境数据库',
          is_active: true,
          created_at: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString(),
          updated_at: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(),
          last_used_at: new Date(Date.now() - 6 * 60 * 60 * 1000).toISOString(),
        },
        {
          id: '3',
          name: '开发环境-Doris',
          host: '192.168.1.102',
          port: 9030,
          username: 'dev_user',
          description: '开发环境数据库',
          is_active: false,
          created_at: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
          updated_at: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString(),
        },
      ]
      setConnections(mockConnections)
    } finally {
      setLoading(false)
    }
  }

  // 创建连接
  const handleCreateConnection = async (data: CreateConnectionData) => {
    setFormLoading(true)
    try {
      const response = await createConnection(data)
      if (response.success) {
        message.success('连接创建成功')
        setFormVisible(false)
        setEditingConnection(undefined)
        await loadConnections()
      }
    } catch (error) {
      console.error('Failed to create connection:', error)
      message.error('连接创建失败')
    } finally {
      setFormLoading(false)
    }
  }

  // 更新连接
  const handleUpdateConnection = async (data: UpdateConnectionData) => {
    if (!editingConnection) return

    setFormLoading(true)
    try {
      const response = await updateConnection(editingConnection.id, data)
      if (response.success) {
        message.success('连接更新成功')
        setFormVisible(false)
        setEditingConnection(undefined)
        await loadConnections()
      }
    } catch (error) {
      console.error('Failed to update connection:', error)
      message.error('连接更新失败')
    } finally {
      setFormLoading(false)
    }
  }

  // 删除连接
  const handleDeleteConnection = async (id: string) => {
    try {
      const response = await deleteConnection(id)
      if (response.success) {
        message.success('连接删除成功')
        await loadConnections()
      }
    } catch (error) {
      console.error('Failed to delete connection:', error)
      message.error('连接删除失败')
    }
  }

  // 测试连接
  const handleTestConnection = async (id: string) => {
    try {
      const response = await testConnection(id)
      if (response.success) {
        const result = response.data
        if (result.success) {
          message.success(`连接测试成功 (${result.response_time}ms)`)
        } else {
          message.error(`连接测试失败: ${result.message}`)
        }
      }
    } catch (error) {
      console.error('Failed to test connection:', error)
      message.error('连接测试失败')
    }
  }

  // 切换连接状态
  const handleToggleStatus = async (id: string, isActive: boolean) => {
    try {
      const response = await updateConnection(id, { is_active: isActive })
      if (response.success) {
        message.success(`连接已${isActive ? '启用' : '禁用'}`)
        await loadConnections()
      }
    } catch (error) {
      console.error('Failed to toggle connection status:', error)
      message.error('状态切换失败')
    }
  }

  // 打开新建连接表单
  const handleCreateNew = () => {
    setEditingConnection(undefined)
    setFormVisible(true)
  }

  // 打开编辑连接表单
  const handleEdit = (connection: Connection) => {
    setEditingConnection(connection)
    setFormVisible(true)
  }

  // 查看连接统计
  const handleViewStats = (connection: Connection) => {
    setSelectedConnection(connection)
    setStatsVisible(true)
  }

  // 查看数据库结构
  const handleViewSchema = (connection: Connection) => {
    setSelectedConnection(connection)
    setSchemaVisible(true)
  }

  // 关闭模态框
  const handleCloseModals = () => {
    setStatsVisible(false)
    setSchemaVisible(false)
    setSelectedConnection(null)
  }

  // 计算统计数据
  const getConnectionStats = () => {
    const total = connections.length
    const active = connections.filter(conn => conn.is_active).length
    const recentlyUsed = connections.filter(conn => 
      conn.last_used_at && 
      new Date(conn.last_used_at).getTime() > Date.now() - 24 * 60 * 60 * 1000
    ).length

    return { total, active, inactive: total - active, recentlyUsed }
  }

  useEffect(() => {
    loadConnections()
  }, [])

  const stats = getConnectionStats()

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: 24,
        }}>
          <Title level={2} style={{ margin: 0 }}>
            连接管理
          </Title>
          
          <Space>
            <Button
              icon={<ReloadOutlined />}
              onClick={loadConnections}
              loading={loading}
            >
              刷新
            </Button>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreateNew}
            >
              新建连接
            </Button>
          </Space>
        </div>

        {/* 统计卡片 */}
        <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="总连接数"
                value={stats.total}
                prefix={<DatabaseOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="活跃连接"
                value={stats.active}
                prefix={<CheckCircleOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="禁用连接"
                value={stats.inactive}
                prefix={<ExclamationCircleOutlined />}
                valueStyle={{ color: '#faad14' }}
              />
            </Card>
          </Col>
          
          <Col xs={24} sm={12} md={6}>
            <Card>
              <Statistic
                title="24h内使用"
                value={stats.recentlyUsed}
                prefix={<CheckCircleOutlined />}
                valueStyle={{ color: '#722ed1' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 安全提示 */}
        <Alert
          message="连接安全提示"
          description="请定期检查连接配置，确保使用最小权限原则。建议为不同环境使用不同的数据库账户，并定期更新密码。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />

        {/* 连接列表 */}
        <ConnectionList
          connections={connections}
          loading={loading}
          onEdit={handleEdit}
          onDelete={handleDeleteConnection}
          onTest={handleTestConnection}
          onToggleStatus={handleToggleStatus}
          onViewStats={handleViewStats}
          onViewSchema={handleViewSchema}
        />
      </Card>

      {/* 连接表单 */}
      <ConnectionForm
        visible={formVisible}
        connection={editingConnection}
        onCancel={() => {
          setFormVisible(false)
          setEditingConnection(undefined)
        }}
        onSubmit={editingConnection ? handleUpdateConnection : handleCreateConnection}
        loading={formLoading}
      />

      {/* 连接统计 */}
      <ConnectionStats
        visible={statsVisible}
        connection={selectedConnection}
        onClose={handleCloseModals}
      />

      {/* 数据库结构 */}
      <DatabaseSchema
        visible={schemaVisible}
        connection={selectedConnection}
        onClose={handleCloseModals}
      />
    </div>
  )
}

export default ConnectionManager